package mo.offer_special;

import java.util.ArrayList;
import java.util.List;

public class L081 {

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> results = new ArrayList<>();
        List<Integer> combination = new ArrayList<>();
        dfs(candidates, target, results, combination, 0);
        return results;
    }


    private void  dfs(int[] candidates, int target, List<List<Integer>> results, List<Integer> combination, int idx) {
        if (idx == candidates.length) {
            return;
        }
        if (target == 0) {
            results.add(new ArrayList<>(combination));
            return;
        }
        dfs(candidates, target, results, combination, idx+1);
        if (target - candidates[idx] >= 0) {
            //加了元素，在递归中处理了，所以在最后一步要去掉
            combination.add(candidates[idx]);
            dfs(candidates, target - candidates[idx], results, combination, idx);
            combination.remove(combination.size() - 1);
        }
    }



}
